Hooks
Hooks provide an extensible event-driven system for automating actions in response to agent commands and events. Hooks are automatically discovered from directories and can be inspected withopenclaw hooks, while hook-pack installation and updates now go through openclaw plugins.
Getting Oriented
Hooks are small scripts that run when something happens. There are two kinds:- Hooks (this page): run inside the Gateway when agent events fire, like
/new,/reset,/stop, or lifecycle events. - Webhooks: external HTTP webhooks that let other systems trigger work in OpenClaw. See Webhook Hooks or use
openclaw webhooksfor Gmail helper commands.
openclaw hooks list shows both standalone hooks and plugin-managed hooks.
Common uses:
- Save a memory snapshot when you reset a session
- Keep an audit trail of commands for troubleshooting or compliance
- Trigger follow-up automation when a session starts or ends
- Write files into the agent workspace or call external APIs when events fire
Overview
The hooks system allows you to:- Save session context to memory when
/newis issued - Log all commands for auditing
- Trigger custom automations on agent lifecycle events
- Extend OpenClaw’s behavior without modifying core code
Getting Started
Bundled Hooks
OpenClaw ships with four bundled hooks that are automatically discovered:- 💾 session-memory: Saves session context to your agent workspace (default
~/.openclaw/workspace/memory/) when you issue/newor/reset - 📎 bootstrap-extra-files: Injects additional workspace bootstrap files from configured glob/path patterns during
agent:bootstrap - 📝 command-logger: Logs all command events to
~/.openclaw/logs/commands.log - 🚀 boot-md: Runs
BOOT.mdwhen the gateway starts (requires internal hooks enabled)
Onboarding
During onboarding (openclaw onboard), you’ll be prompted to enable recommended hooks. The wizard automatically discovers eligible hooks and presents them for selection.
Trust Boundary
Hooks run inside the Gateway process. Treat bundled hooks, managed hooks, andhooks.internal.load.extraDirs as trusted local code. Workspace hooks under <workspace>/hooks/ are repo-local code, so OpenClaw requires an explicit enable step before loading them.
Hook Discovery
Hooks are automatically discovered from these directories, in order of increasing override precedence:- Bundled hooks: shipped with OpenClaw; located at
<openclaw>/dist/hooks/bundled/for npm installs (or a siblinghooks/bundled/for compiled binaries) - Plugin hooks: hooks bundled inside installed plugins (see Plugin hooks)
- Managed hooks:
~/.openclaw/hooks/(user-installed, shared across workspaces; can override bundled and plugin hooks). Extra hook directories configured viahooks.internal.load.extraDirsare also treated as managed hooks and share the same override precedence. - Workspace hooks:
<workspace>/hooks/(per-agent, disabled by default until explicitly enabled; cannot override hooks from other sources)
Hook Packs (npm/archives)
Hook packs are standard npm packages that export one or more hooks viaopenclaw.hooks in
package.json. Install them with:
@latest stay on the stable track. If npm resolves either of
those to a prerelease, OpenClaw stops and asks you to opt in explicitly with a
prerelease tag such as @beta/@rc or an exact prerelease version.
Example package.json:
HOOK.md and a handler file. The loader tries handler.ts, handler.js, index.ts, index.js in order.
Hook packs can ship dependencies; they will be installed under ~/.openclaw/hooks/<id>.
Each openclaw.hooks entry must stay inside the package directory after symlink
resolution; entries that escape are rejected.
Security note: openclaw plugins install installs hook-pack dependencies with npm install --ignore-scripts
(no lifecycle scripts). Keep hook pack dependency trees “pure JS/TS” and avoid packages that rely
on postinstall builds.
Hook Structure
HOOK.md Format
TheHOOK.md file contains metadata in YAML frontmatter plus Markdown documentation:
Metadata Fields
Themetadata.openclaw object supports:
emoji: Display emoji for CLI (e.g.,"💾")events: Array of events to listen for (e.g.,["command:new", "command:reset"])export: Named export to use (defaults to"default")homepage: Documentation URLos: Required platforms (e.g.,["darwin", "linux"])requires: Optional requirementsbins: Required binaries on PATH (e.g.,["git", "node"])anyBins: At least one of these binaries must be presentenv: Required environment variablesconfig: Required config paths (e.g.,["workspace.dir"])
always: Bypass eligibility checks (boolean)install: Installation methods (for bundled hooks:[{"id":"bundled","kind":"bundled"}])
Handler Implementation
Thehandler.ts file exports a HookHandler function:
Event Context
Each event includes:Event Types
Command Events
Triggered when agent commands are issued:command: All command events (general listener)command:new: When/newcommand is issuedcommand:reset: When/resetcommand is issuedcommand:stop: When/stopcommand is issued
Session Events
session:compact:before: Right before compaction summarizes historysession:compact:after: After compaction completes with summary metadata
type: "session" with action: "compact:before" / action: "compact:after"; listeners subscribe with the combined keys above.
Specific handler registration uses the literal key format ${type}:${action}. For these events, register session:compact:before and session:compact:after.
session:compact:before context fields:
sessionId: internal session UUIDmissingSessionKey: true when no session key was availablemessageCount: number of messages before compactiontokenCount: token count before compaction (may be absent)messageCountOriginal: message count from the full untruncated session historytokenCountOriginal: token count of the full original history (may be absent)
session:compact:after context fields (in addition to sessionId and missingSessionKey):
messageCount: message count after compactiontokenCount: token count after compaction (may be absent)compactedCount: number of messages that were compacted/removedsummaryLength: character length of the generated compaction summarytokensBefore: token count from before compaction (for delta calculation)tokensAfter: token count after compactionfirstKeptEntryId: ID of the first message entry retained after compaction
Agent Events
agent:bootstrap: Before workspace bootstrap files are injected (hooks may mutatecontext.bootstrapFiles)
Gateway Events
Triggered when the gateway starts:gateway:startup: After channels start and hooks are loaded
Session Patch Events
Triggered when session properties are modified:session:patch: When a session is updated
Session Event Context
Session events include rich context about the session and changes:session:patch events. Standard WebChat clients are blocked from patching sessions, so the hook will not fire from those connections.
See SessionsPatchParamsSchema in src/gateway/protocol/schema/sessions.ts for the complete type definition.
Example: Session Patch Logger Hook
Message Events
Triggered when messages are received or sent:message: All message events (general listener)message:received: When an inbound message is received from any channel. Fires early in processing before media understanding. Content may contain raw placeholders like<media:audio>for media attachments that haven’t been processed yet.message:transcribed: When a message has been fully processed, including audio transcription and link understanding. At this point,transcriptcontains the full transcript text for audio messages. Use this hook when you need access to transcribed audio content.message:preprocessed: Fires for every message after all media + link understanding completes, giving hooks access to the fully enriched body (transcripts, image descriptions, link summaries) before the agent sees it.message:sent: When an outbound message is successfully sent
Message Event Context
Message events include rich context about the message:Example: Message Logger Hook
Tool Result Hooks (Plugin API)
These hooks are not event-stream listeners; they let plugins synchronously adjust tool results before OpenClaw persists them.tool_result_persist: transform tool results before they are written to the session transcript. Must be synchronous; return the updated tool result payload orundefinedto keep it as-is. See Agent Loop.
Plugin Hook Events
before_tool_call
Runs before each tool call. Plugins can modify parameters, block the call, or request user approval. Return fields:params: Override tool parameters (merged with original params)block: Set totrueto block the tool callblockReason: Reason shown to the agent when blockedrequireApproval: Pause execution and wait for user approval via channels
requireApproval field triggers native platform approval (Telegram buttons, Discord components, /approve command) instead of relying on the agent to cooperate:
onResolution callback is invoked with the final decision string after the approval resolves, times out, or is cancelled. It runs in-process within the plugin (not sent to the gateway). Use it to persist decisions, update caches, or perform cleanup.
The pluginId field is stamped automatically by the hook runner from the plugin registration. When multiple plugins return requireApproval, the first one (highest priority) wins.
block takes precedence over requireApproval: if the merged hook result has both block: true and a requireApproval field, the tool call is blocked immediately without triggering the approval flow. This ensures a higher-priority plugin’s block cannot be overridden by a lower-priority plugin’s approval request.
If the gateway is unavailable or does not support plugin approvals, the tool call falls back to a soft block using the description as the block reason.
before_install
Runs after the built-in install security scan and before installation continues. OpenClaw fires this hook for interactive skill installs as well as plugin bundle, package, and single-file installs. Default behavior differs by target type:- Plugin installs fail closed on built-in scan
criticalfindings and scan errors unless the operator explicitly usesopenclaw plugins install --dangerously-force-unsafe-install. - Skill installs still surface built-in scan findings and scan errors as warnings and continue by default.
findings: Additional scan findings to surface as warningsblock: Set totrueto block the installblockReason: Human-readable reason shown when blocked
targetType: Install target category (skillorplugin)targetName: Human-readable skill name or plugin id for the install targetsourcePath: Absolute path to the install target content being scannedsourcePathKind: Whether the scanned content is afileordirectoryorigin: Normalized install origin when available (for exampleopenclaw-bundled,openclaw-workspace,plugin-bundle,plugin-package, orplugin-file)request: Provenance for the install request, includingkind,mode, and optionalrequestedSpecifierbuiltinScan: Structured result of the built-in scanner, includingstatus, summary counts, findings, and optionalerrorskill: Skill install metadata whentargetTypeisskill, includinginstallIdand the selectedinstallSpecplugin: Plugin install metadata whentargetTypeisplugin, including the canonicalpluginId, normalizedcontentType, optionalpackageName/manifestId/version, andextensions
targetType: "skill" and a skill object instead of plugin.
Decision semantics:
before_install:{ block: true }is terminal and stops lower-priority handlers.before_install:{ block: false }is treated as no decision.
Compaction lifecycle
Compaction lifecycle hooks exposed through the plugin hook runner:before_compaction: Runs before compaction with count/token metadataafter_compaction: Runs after compaction with compaction summary metadata
Complete Plugin Hook Reference
All 27 hooks registered via the Plugin SDK. Hooks marked sequential run in priority order and can modify results; parallel hooks are fire-and-forget.Model and prompt hooks
| Hook | When | Execution | Returns |
|---|---|---|---|
before_model_resolve | Before model/provider lookup | Sequential | { modelOverride?, providerOverride? } |
before_prompt_build | After model resolved, session messages ready | Sequential | { systemPrompt?, prependContext?, appendSystemContext? } |
before_agent_start | Legacy combined hook (prefer the two above) | Sequential | Union of both result shapes |
llm_input | Immediately before the LLM API call | Parallel | void |
llm_output | Immediately after LLM response received | Parallel | void |
Agent lifecycle hooks
| Hook | When | Execution | Returns |
|---|---|---|---|
agent_end | After agent run completes (success or failure) | Parallel | void |
before_reset | When /new or /reset clears a session | Parallel | void |
before_compaction | Before compaction summarizes history | Parallel | void |
after_compaction | After compaction completes | Parallel | void |
Session lifecycle hooks
| Hook | When | Execution | Returns |
|---|---|---|---|
session_start | When a new session begins | Parallel | void |
session_end | When a session ends | Parallel | void |
Message flow hooks
| Hook | When | Execution | Returns |
|---|---|---|---|
inbound_claim | Before command/agent dispatch; first-claim wins | Sequential | { handled: boolean } |
message_received | After an inbound message is received | Parallel | void |
before_dispatch | After commands parsed, before model dispatch | Sequential | { handled: boolean, text? } |
message_sending | Before an outbound message is delivered | Sequential | { content?, cancel? } |
message_sent | After an outbound message is delivered | Parallel | void |
before_message_write | Before a message is written to session transcript | Sync, sequential | { block?, message? } |
Tool execution hooks
| Hook | When | Execution | Returns |
|---|---|---|---|
before_tool_call | Before each tool call | Sequential | { params?, block?, blockReason?, requireApproval? } |
after_tool_call | After a tool call completes | Parallel | void |
tool_result_persist | Before a tool result is written to transcript | Sync, sequential | { message? } |
Subagent hooks
| Hook | When | Execution | Returns |
|---|---|---|---|
subagent_spawning | Before a subagent session is created | Sequential | { status, threadBindingReady? } |
subagent_delivery_target | After spawning, to resolve delivery target | Sequential | { origin? } |
subagent_spawned | After a subagent is fully spawned | Parallel | void |
subagent_ended | When a subagent session terminates | Parallel | void |
Gateway hooks
| Hook | When | Execution | Returns |
|---|---|---|---|
gateway_start | After the gateway process is fully started | Parallel | void |
gateway_stop | When the gateway is shutting down | Parallel | void |
Install hooks
| Hook | When | Execution | Returns |
|---|---|---|---|
before_install | After built-in security scan, before install proceeds | Sequential | { findings?, block?, blockReason? } |
Two hooks (
tool_result_persist and before_message_write) are synchronous only — they must not return a Promise. Returning a Promise from these hooks is caught at runtime and the result is discarded with a warning.Future Events
The following event types are planned for the internal hook event stream. Note thatsession_start and session_end already exist as Plugin Hook API hooks
but are not yet available as internal hook event keys in HOOK.md metadata:
session:start: When a new session begins (planned for internal hook stream; available as plugin hooksession_start)session:end: When a session ends (planned for internal hook stream; available as plugin hooksession_end)agent:error: When an agent encounters an error
Creating Custom Hooks
1. Choose Location
- Workspace hooks (
<workspace>/hooks/): Per-agent; can add new hook names but cannot override bundled, managed, or plugin hooks with the same name - Managed hooks (
~/.openclaw/hooks/): Shared across workspaces; can override bundled and plugin hooks
2. Create Directory Structure
3. Create HOOK.md
4. Create handler.ts
5. Enable and Test
Configuration
New Config Format (Recommended)
Per-Hook Configuration
Hooks can have custom configuration:Extra Directories
Load hooks from additional directories (treated as managed hooks, same override precedence):Legacy Config Format (Still Supported)
The old config format still works for backwards compatibility:module must be a workspace-relative path. Absolute paths and traversal outside the workspace are rejected.
Migration: Use the new discovery-based system for new hooks. Legacy handlers are loaded after directory-based hooks.
CLI Commands
List Hooks
Hook Information
Check Eligibility
Enable/Disable
Bundled hook reference
session-memory
Saves session context to memory when you issue/new or /reset.
Events: command:new, command:reset
Requirements: workspace.dir must be configured
Output: <workspace>/memory/YYYY-MM-DD-slug.md (defaults to ~/.openclaw/workspace)
What it does:
- Uses the pre-reset session entry to locate the correct transcript
- Extracts the last 15 user/assistant messages from the conversation (configurable)
- Uses LLM to generate a descriptive filename slug
- Saves session metadata to a dated memory file
2026-01-16-vendor-pitch.md2026-01-16-api-design.md2026-01-16-1430.md(fallback timestamp if slug generation fails)
bootstrap-extra-files
Injects additional bootstrap files (for example monorepo-localAGENTS.md / TOOLS.md) during agent:bootstrap.
Events: agent:bootstrap
Requirements: workspace.dir must be configured
Output: No files written; bootstrap context is modified in-memory only.
Config:
paths(string[]): glob/path patterns to resolve from the workspace.patterns(string[]): alias ofpaths.files(string[]): alias ofpaths.
- Paths are resolved relative to workspace.
- Files must stay inside workspace (realpath-checked).
- Only recognized bootstrap basenames are loaded (
AGENTS.md,SOUL.md,TOOLS.md,IDENTITY.md,USER.md,HEARTBEAT.md,BOOTSTRAP.md,MEMORY.md,memory.md). - For subagent/cron sessions a narrower allowlist applies (
AGENTS.md,TOOLS.md,SOUL.md,IDENTITY.md,USER.md).
command-logger
Logs all command events to a centralized audit file. Events:command
Requirements: None
Output: ~/.openclaw/logs/commands.log
What it does:
- Captures event details (command action, timestamp, session key, sender ID, source)
- Appends to log file in JSONL format
- Runs silently in the background
boot-md
RunsBOOT.md when the gateway starts (after channels start).
Internal hooks must be enabled for this to run.
Events: gateway:startup
Requirements: workspace.dir must be configured
What it does:
- Reads
BOOT.mdfrom your workspace - Runs the instructions via the agent runner
- Sends any requested outbound messages via the message tool
Best Practices
Keep Handlers Fast
Hooks run during command processing. Keep them lightweight:Handle Errors Gracefully
Always wrap risky operations:Filter Events Early
Return early if the event isn’t relevant:Use Specific Event Keys
Specify exact events in metadata when possible:Debugging
Enable Hook Logging
The gateway logs hook loading at startup:Check Discovery
List all discovered hooks:Check Registration
In your handler, log when it’s called:Verify Eligibility
Check why a hook isn’t eligible:Testing
Gateway Logs
Monitor gateway logs to see hook execution:Test Hooks Directly
Test your handlers in isolation:Architecture
Core Components
src/hooks/types.ts: Type definitionssrc/hooks/workspace.ts: Directory scanning and loadingsrc/hooks/frontmatter.ts: HOOK.md metadata parsingsrc/hooks/config.ts: Eligibility checkingsrc/hooks/hooks-status.ts: Status reportingsrc/hooks/loader.ts: Dynamic module loadersrc/cli/hooks-cli.ts: CLI commandssrc/gateway/server-startup.ts: Loads hooks at gateway startsrc/auto-reply/reply/commands-core.ts: Triggers command events
Discovery Flow
Event Flow
Troubleshooting
Hook Not Discovered
-
Check directory structure:
-
Verify HOOK.md format:
-
List all discovered hooks:
Hook Not Eligible
Check requirements:- Binaries (check PATH)
- Environment variables
- Config values
- OS compatibility
Hook Not Executing
-
Verify hook is enabled:
- Restart your gateway process so hooks reload.
-
Check gateway logs for errors:
Handler Errors
Check for TypeScript/import errors:Migration Guide
From Legacy Config to Discovery
Before:-
Create hook directory:
-
Create HOOK.md:
-
Update config:
-
Verify and restart your gateway process:
- Automatic discovery
- CLI management
- Eligibility checking
- Better documentation
- Consistent structure